import configUrl from "@/common/config";
import { useUserStore } from "@/store/modules/user";
import request from "@/utils/request";
interface UploadsData extends Record<string, string> {
  file: string;
}

//  uniapp上传文件
export function uploadsUni(
  data: UploadsData,
  callback?: Function
): Promise<IResponse<any>> {
  return new Promise((resolve, reject) => {
    const userStore = useUserStore();
    const token = userStore.getToken;
    const { file, ...formData } = data;
    console.log(file);

    let fileObj:any={}
    console.log(typeof file);
     if(Object.prototype.toString.call(file)==='[object File]'){
      fileObj.file=file
     }else{
      fileObj.filePath=file
     }
    


    const uploadTask = uni.uploadFile({
      url:configUrl.hosts+ "/upload", 
      name: "file",
      header: {
        Authorization: token ? "Bearer " + token : "",
      },
      ...fileObj,
      formData,
      timeout: 50000,
      success: (uploadFileRes) => {
        const data = JSON.parse(uploadFileRes.data);
        if (data.code == 0) {
          resolve(data);
        } else {
          reject(data);
        }
        console.log(uploadFileRes);
      },
      fail: (err) => {
        reject(err);
        console.log(err);
      },
    });
    uploadTask.onProgressUpdate((res) => callback && callback(res));
  });
}

interface UploadFace extends Record<string, any> {
  file: File;
}

/**
 * h5 上传的方法，请结合自己封装的request使用
 * @param data
 * @param callback 上传进度的回调
 * @returns
 */
export function uploads(
  data: UploadFace,
  callback?: Function
): Promise<IResponse<any>> {
  var formData = new FormData();

  for (let key in data) {
    console.log(key);
    
    formData.append('file', data[key]);
  }
  console.log(data);
  console.log(formData);
  

  return request({
    url: "/upload/",
    method: "POST",
    headers: {
      "Content-type": "multipart/form-data",
    },
    timeout: 100000,
    data: formData,
    onUploadProgress: (progressEvent: any) =>
      callback && callback(progressEvent),
  });
}
